import java.util.ArrayList;
import java.util.List;

// 二叉树的锯齿形层序遍历
// 测试链接 : https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/
public class ZigzagLevelOrderTraversal {
    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;
    }

    public static int MAX = 2001;

    public static TreeNode[] arr= new TreeNode[MAX];
    public static int l,r;

    public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();

        if(root == null) {
            return ret;
        }
        arr[r++] = root;
        boolean flag = true;
        while (l < r){
            int size = r - l;

            int right = r-1;
            int left = l;
            List<Integer> list = new ArrayList<>();
            if(!flag) {
                for(int i = 0; i < size; ++i) {
                    TreeNode node = arr[l++];
                    list.add(node.val);

                    TreeNode treeNode = arr[right--];
                    if(treeNode.left != null) {
                        arr[r++] = treeNode.left;
                    }
                    if(treeNode.right != null){
                        arr[r++] = treeNode.right;
                    }
                }
            }else {
                for(int i = 0; i < size; ++i) {
                    TreeNode node = arr[l++];
                    list.add(node.val);

                    TreeNode treeNode = arr[right--];
                    if(treeNode.right != null){
                        arr[r++] = treeNode.right;
                    }
                    if(treeNode.left != null) {
                        arr[r++] = treeNode.left;
                    }
                }
            }
            flag = !flag;
            ret.add(list);
        }
        return ret;
    }
}
